<template>
  <a-modal
    v-model:open="visible"
    title="个人资料"
    :width="600"
    :confirm-loading="loading"
    ok-text="保存"
    cancel-text="取消"
    @ok="handleSave"
    @cancel="handleCancel"
  >
    <div class="profile-content">
      <!-- 头像区域 -->
      <div class="avatar-section">
        <div class="avatar-container">
          <div class="avatar-upload">
            <a-upload
              v-model:file-list="fileList"
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              :custom-request="handleAvatarUpload"
            >
              <div v-if="formData.avatarUrl" class="avatar-preview">
                <img :src="formData.avatarUrl" alt="avatar" />
                <div class="avatar-overlay">
                  <CloudUploadOutlined />
                  <div class="upload-text">更换头像</div>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <a-avatar
                  :size="80"
                  :style="{
                    background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
                    fontSize: '32px',
                    fontWeight: '600'
                  }"
                >
                  {{ (formData.nickname || formData.username || 'U')[0]?.toUpperCase() }}
                </a-avatar>
                <div class="upload-overlay">
                  <CloudUploadOutlined />
                  <div class="upload-text">上传头像</div>
                </div>
              </div>
            </a-upload>
          </div>
        </div>
      </div>

      <!-- 基本信息表单 -->
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
        class="profile-form"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户名" name="username">
              <a-input
                v-model:value="formData.username"
                placeholder="请输入用户名"
                :disabled="true"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" name="email">
              <a-input
                  v-model:value="formData.email"
                  placeholder="请输入邮箱地址"
                  type="email"
                  :disabled="true"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="昵称" name="nickname">
              <a-input
                  v-model:value="formData.nickname"
                  placeholder="请输入昵称"
                  :max-length="20"
                  show-count
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="性别" name="gender">
              <a-select
                v-model:value="formData.gender"
                placeholder="请选择性别"
                allow-clear
              >
                <a-select-option :value="0">未知</a-select-option>
                <a-select-option :value="1">男</a-select-option>
                <a-select-option :value="2">女</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="生日" name="birthday">
              <a-date-picker
                v-model:value="formData.birthday"
                placeholder="请选择生日"
                style="width: 100%"
                format="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { CloudUploadOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores'
import { useAuthStore } from '@/stores/modules/auth'
import { Codewin } from '@/api/generated/Codewin'
import type { FormInstance, UploadProps } from 'ant-design-vue'
import type { UpdateUserRequest } from '@/api/generated/data-contracts'
import dayjs, { type Dayjs } from 'dayjs'

// Props 和 Emits
interface Props {
  open: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// Store
const userStore = useUserStore()
const authStore = useAuthStore()

// API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api'
})

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()
const fileList = ref<any[]>([])

// 表单数据
interface FormData {
  username: string
  nickname: string
  email: string
  gender: number | null
  birthday: Dayjs | null
  avatarUrl: string
}

const formData = ref<FormData>({
  username: '',
  nickname: '',
  email: '',
  gender: null,
  birthday: null,
  avatarUrl: ''
})

// 表单验证规则
const rules = {
  nickname: [
    { max: 20, message: '昵称不能超过20个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 监听弹窗显示状态
watch(() => props.open, (newVal) => {
  visible.value = newVal
  if (newVal) {
    loadUserProfile()
  }
})

watch(visible, (newVal) => {
  if (!newVal) {
    emit('update:open', false)
  }
})

// 方法
const loadUserProfile = async () => {
  // 首先尝试从API获取最新的用户信息
  try {
    const headers: Record<string, string> = {}
    if (authStore.token) {
      headers['Authorization'] = `Bearer ${authStore.token}`
    }

    const response = await api.getCurrentUserInfo({
      headers
    })

    if (response.data?.code === 0 && response.data.data) {
      const userData = response.data.data
      formData.value = {
        username: userData.username || '',
        nickname: userData.nickname || '',
        email: userData.email || '',
        gender: typeof userData.gender === 'number' ? userData.gender : null,
        birthday: userData.birthday ? dayjs(userData.birthday) : null,
        avatarUrl: userData.avatar || ''
      }
      return
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }

  // 如果API调用失败，回退到使用store中的数据
  const profile = userStore.profile
  if (profile) {
    formData.value = {
      username: profile.username || '',
      nickname: profile.nickname || '',
      email: profile.email || '',
      gender: null, // UserProfile接口中没有gender字段
      birthday: null, // UserProfile接口中没有birthday字段
      avatarUrl: profile.avatar || ''
    }
  }
}

// 文件上传前的验证
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true // 允许上传，由custom-request处理
}

// 头像上传处理函数
const handleAvatarUpload: UploadProps['customRequest'] = async (options) => {
  const { file, onSuccess, onError } = options
  if (file instanceof File) {
    try {
      // 设置Authorization header
      const headers: Record<string, string> = {}
      if (authStore.token) {
        headers['Authorization'] = `Bearer ${authStore.token}`
      }

      const response = await api.uploadFile({ file }, {
        headers
      })

      if (response.data?.code === 0 && response.data?.data) {
        formData.value.avatarUrl = response.data.data
        message.success('头像上传成功！')
        onSuccess?.(response.data.data)
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('头像上传失败:', error)
      message.error('头像上传失败，请重试')
      onError?.(error as Error)
    }
  }
}

const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    // 准备更新数据 - 使用UpdateUserRequest接口支持的字段
    const updateData: UpdateUserRequest = {
      nickname: formData.value.nickname,
      avatar: formData.value.avatarUrl
    }

    // 添加gender字段（包括0值-未知）
    if (typeof formData.value.gender === 'number') {
      updateData.gender = formData.value.gender
    }

    // 添加birthday字段（如果有值）
    if (formData.value.birthday) {
      updateData.birthday = dayjs(formData.value.birthday).format('YYYY-MM-DD')
    }

    // 设置Authorization header
    const headers: Record<string, string> = {}
    if (authStore.token) {
      headers['Authorization'] = `Bearer ${authStore.token}`
    }

    // 直接调用后端API更新用户信息
    const response = await api.updateUserInfo(updateData, {
      headers
    })

    if (response.data?.code === 0) {
      // 更新本地用户信息
      await userStore.fetchUserInfo()

      message.success('个人资料更新成功')
      emit('success')
      emit('update:open', false)
    } else {
      throw new Error(response.data?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
    if (error && typeof error === 'object' && 'errorFields' in error) {
      // 表单验证错误
      return
    }
    message.error('更新个人资料失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  emit('update:open', false)
}
</script>

<style scoped>
.profile-content {
  padding: 16px 0;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 32px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.avatar-display {
  position: relative;
}

.avatar-preview {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #e5e7eb;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
}

.profile-info {
  max-width: 100%;
}

.info-item {
  margin-bottom: 20px;
}

.info-label {
  display: block;
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-value {
  padding: 8px 12px;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  color: #374151;
  min-height: 32px;
  display: flex;
  align-items: center;
}

.info-value.avatar-url {
  word-break: break-all;
  font-size: 12px;
  color: #6b7280;
}

.disabled-input {
  background-color: #f9fafb !important;
  border-color: #e5e7eb !important;
  color: #6b7280 !important;
  cursor: not-allowed;
}

.disabled-input:hover {
  border-color: #e5e7eb !important;
}

.disabled-input:focus {
  border-color: #e5e7eb !important;
  box-shadow: none !important;
}
</style>
